package com.dalei.vdsmanager.account.action;

import java.util.Map;

import com.dalei.vdsmanager.security.dao.User;
import com.dalei.vdsmanager.security.service.UserService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class ChangeUserPasswordAction extends ActionSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = -8271037756602594523L;

	private UserService userService;

	private String oldPassword;

	private String password;

	private String repeatPassword;

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public String getOldPassword() {
		return oldPassword;
	}

	public void setOldPassword(String oldPassword) {
		this.oldPassword = oldPassword;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getRepeatPassword() {
		return repeatPassword;
	}

	public void setRepeatPassword(String repeatPassword) {
		this.repeatPassword = repeatPassword;
	}

	@Override
	public String execute() throws Exception {
		// TODO Auto-generated method stub
		// return super.execute();
		Map<String, Object> session = ActionContext.getContext().getSession();
		String lastName = (String) session.get("SPRING_SECURITY_LAST_USERNAME");
		User u = userService.getUserByUserName(lastName);
		userService.changePassword(u.getId(), password);
		return SUCCESS;
	}

	@Override
	public void validate() {
		// TODO Auto-generated method stub
		super.validate();
		Map<String, Object> session = ActionContext.getContext().getSession();
		String lastName = (String) session.get("SPRING_SECURITY_LAST_USERNAME");
		User u = userService.getUserByUserName(lastName);
		if (u == null) {
			addActionError(getText("changeUserPassword.invalidUser"));
		} else {
			if (oldPassword == null) {
				addFieldError("oldPassword",
						getText("changeUserPassword.oldPassword.null"));
			} else {
				if (!userService.validateUser(lastName, oldPassword)) {
					addFieldError("oldPassword",
							getText("changeUserPassword.oldPassword.invalid"));
				}
			}
			if (password == null) {
				addFieldError("password",
						getText("changeUserPassword.password.null"));
			}
			if (repeatPassword == null) {
				addFieldError("repeatPassword",
						getText("changeUserPassword.repeatPassword.null"));
			} else {
				if (!repeatPassword.equals(password)) {
					addFieldError(
							"repeatPassword",
							getText("changeUserPassword.repeatPassword.notMatch"));
				}
			}
		}
	}
}
